package com.chy.controller;

import com.chy.bean.Gallery;
import com.chy.bean.Order;
import com.chy.service.OrderService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
import static com.chy.jdbcutil.Constant.REDIRECT;

@Controller
@RequestMapping("/order")
public class OrderController {

    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public  String load(Model model){
        //获取用户列表
        List<Order> all = SpringUtil.applicationContext().getBean(OrderService.class).getAll();
        model.addAttribute("orderList",all);
        List<Gallery> allImg = SpringUtil.applicationContext().getBean(OrderService.class).getAllImg();
        model.addAttribute("allImg",allImg);
        return "order/list";
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    public  String delete(@PathVariable("id") Integer id){
        //执行删除操作
        System.out.println("id = " + id);
        SpringUtil.applicationContext().getBean(OrderService.class).delete(Order.builder().id(id).build());
        return REDIRECT;
    }

    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public  String updateOrder(Order order,HttpServletRequest request){
        //执行修改操作
        String updateImgId = request.getParameter("update_select");
        System.out.println("id = " + order.getId());
        SpringUtil.applicationContext().getBean(OrderService.class).update(order,updateImgId);
        return REDIRECT;
    }

    @RequestMapping(value = "/save",method = RequestMethod.POST)
    public  String save(Order order,HttpServletRequest request){
        //执行更新操作
        String addImgId = request.getParameter("add_select");
        SpringUtil.applicationContext().getBean(OrderService.class).add(order,addImgId);
        return REDIRECT;
    }

    @RequestMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) throws Exception
    {
        String name = file.getOriginalFilename();
        SpringUtil.applicationContext().getBean(OrderService.class).uploading(name);
        file.transferTo(new File("C:/Users/Administrator/IdeaProjects/SpringMVC-HomeWork/src/main/webapps/static/"+file.getOriginalFilename()));
        return REDIRECT;
    }
}
